package com.yami.shop.service;


import com.yami.shop.config.CalculateRequest;
import com.yami.shop.config.CalculateResponse;
import com.yami.shop.config.DeviceConfig;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class DevicePriceService {


    @Autowired
    private  DeviceConfig deviceConfig;

    public CalculateResponse calculatePrice(CalculateRequest request) {
        CalculateResponse response = new CalculateResponse();
        response.setTotalPrice(deviceConfig.getBasePrice());
        response.setDetails(new ArrayList<>());

        for (CalculateRequest.AttributeSelection selection : request.getSelections()) {
            CalculateResponse.PriceDetail detail = new CalculateResponse.PriceDetail();
            detail.setAttribute(selection.getAttribute());
            detail.setSelectedValues(selection.getValues());

            Optional<DeviceConfig.AttributeConfig> attributeConfig = deviceConfig.getAttributes().stream()
                    .filter(a -> a.getName().equals(selection.getAttribute()))
                    .findFirst();

            if (attributeConfig.isPresent()) {
                int attributePrice = calculateAttributePrice(attributeConfig.get(), selection);
                detail.setPrice(attributePrice);
                response.setTotalPrice(response.getTotalPrice() + attributePrice);
            }

            response.getDetails().add(detail);
        }

        return response;
    }

    private int calculateAttributePrice(DeviceConfig.AttributeConfig config, CalculateRequest.AttributeSelection selection) {
        return selection.getValues().stream()
                .mapToInt(value -> {
                    return config.getOptions().stream()
                            .filter(o -> o.getValue().equals(value))
                            .findFirst()
                            .map(DeviceConfig.OptionConfig::getPrice)
                            .orElse(0);
                })
                .sum();
    }
}
